Page({
    data: {
      tabIndex: 0,
      currentCategory: '全部',
      pets: [],
      filteredPets: []
    },
  
    onShow() {
      this.setData({ 
        tabIndex: 0,
        currentCategory: '全部'
      });
      this.fetchPets();
    },
  
    fetchPets() {
        wx.request({
          url: 'http://localhost:3000/pets',
          success: (res) => {
            console.log(res);
            if (res.statusCode === 200) {
              const rawPets = res.data.data
              const pets = rawPets.map(item => ({
                id: item.id,
                name: item.name,
                age: item.age,
                price: Number(item.price), 
                img: item.img,
                type: item.type,
                description: item.description,
                distance: (Math.random() * 3 + 1).toFixed(1) + ' km'
              }));
      
              this.setData({
                pets,
                filteredPets: pets
              });
            } else {
              wx.showToast({ title: '获取失败', icon: 'error' });
            }
          },
          fail: () => {
            wx.showToast({ title: '网络错误', icon: 'error' });
          }
        });
      },      
  
    // 分类筛选
    onCategoryChange(e) {
      const type = e.detail.type;
      const filtered = type === 'all'
        ? this.data.pets
        : this.data.pets.filter(pet => pet.type === type);
      
      this.setData({
        currentCategory: type,
        filteredPets: filtered
      });
    },
  
    // 点击宠物卡片跳转详情页
    onPetCardTap(e) {
        const petId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/pet-detail/pet-detail?id=${petId}`
        });
    },
  
    // 跳转搜索页
    goToSeekPets() {
      wx.navigateTo({
        url: '/pages/pet-seek/pet-seek',
      });
    },
  
    // tabbar 切换
    onTabChange(e) {
      const index = e.detail.index;
      const tabPages = [
        '/pages/index/index',
        '/pages/cart/cart',
        '/pages/map-pet/map-pet',
        '/pages/settings/settings'
      ];
  
      if (index === this.data.tabIndex) return;
  
      wx.switchTab({
        url: tabPages[index]
      });
    }
  });
  